package com.lw.common.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import com.hjq.toast.Toaster
import java.io.*

object ScannerUtils {
    // 首先保存图片
    fun saveImageToGallery(context: Context, bitmap: Bitmap?, type: ScannerType): String {
        val appDir = File(Environment.getExternalStorageDirectory().absolutePath, "android")
        if (!appDir.exists()) {
            // 目录不存在 则创建
            appDir.mkdirs()
        }
        //下面的CompressFormat.PNG/CompressFormat.JPEG， 这里对应.png/.jpeg
        val fileName = "signature.png"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bitmap!!.compress(Bitmap.CompressFormat.PNG, 100, fos) // 保存bitmap至本地
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (type == ScannerType.RECEIVER) {
                ScannerByReceiver(context, file.absolutePath)
            } else if (type == ScannerType.MEDIA) {
                ScannerByMedia(context, file.absolutePath)
            }
            if (bitmap != null && !bitmap.isRecycled) {

                //当存储大图片时，为避免出现OOM ，及时回收Bitmap
                bitmap.recycle()

                // 通知系统回收
                System.gc()
            }

            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(
                    context.contentResolver,
                    file.absolutePath, fileName, null
                )
                Toaster.show("保存成功")
            } catch (e: FileNotFoundException) {
                Toaster.show("保存失败")
                e.printStackTrace()
            }
            // 最后通知图库更新
            context.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(File(file.path))
                )
            )

            //返回保存的图片路径
            return file.absolutePath
        }
    }

    //删除图片
    fun deleteSuccess(context: Context, filePath: String) {
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val mContentResolver = context.contentResolver
        val where = MediaStore.Images.Media.DATA + "='" + filePath + "'"
        //删除图片
        mContentResolver.delete(uri, where, null)
    }

    /** Receiver扫描更新图库图片  */
    private fun ScannerByReceiver(context: Context, path: String) {
        context.sendBroadcast(
            Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://$path")
            )
        )
        Log.v("TAG", "receiver scanner completed")
    }

    /** MediaScanner 扫描更新图片图片  */
    private fun ScannerByMedia(context: Context, path: String) {
        MediaScannerConnection.scanFile(context, arrayOf(path), null, null)
        Log.v("TAG", "media scanner completed")
    }

    fun saveToSystemGallery(context: Context?, bmp: Bitmap) {
        // 首先保存图片
        val appDir = File(Environment.getExternalStorageDirectory(), "vgmap")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

//        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        // 最后通知图库更新
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
    }

    //    private void createFile(Context context,String mimeType, String fileName) {
    //        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    //
    //        // Filter to only show results that can be "opened", such as
    //        // a file (as opposed to a list of contacts or timezones).
    //        intent.addCategory(Intent.CATEGORY_OPENABLE);
    //
    //        // Create a file with the requested MIME type.
    //        intent.setType(mimeType);
    //        intent.putExtra(Intent.EXTRA_TITLE, fileName);
    //        (Activity)context.startActivityForResult(intent, 43);
    //        context.start
    //    }
    fun saveBitmapFile(bitmap: Bitmap, file: File?) {
        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: FileNotFoundException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } catch (e: IOException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
    }

    // 扫描的两种方式
    enum class ScannerType {
        RECEIVER, MEDIA
    }
}